<template>
  <div>
    <h3>查看留言</h3>
    <div class="view" v-if="message">
      <div class="item">
        <div class="field">主题：</div>
        <div class="value">{{ message.title }}</div>
      </div>
      <div class="item">
        <div class="field">作者：</div>
        <div class="value">{{ message.author }}</div>
      </div>
      <div class="item">
        <div class="field">日期：</div>
        <div class="value">{{ message.create_date }}</div>
      </div>
      <div class="item">
        <div class="field">内容：</div>
        <div class="value">
          {{ message.content }}
        </div>
      </div>
      <div class="item reply" v-if="message?.reply_content">
        <div class="field">回复：</div>
        <div class="value">
          {{ message?.reply_content }}
        </div>
      </div>
      <div class="item reply-btn" v-else-if="store?.token && store.status === 0 && [1,2].includes(store.role)">
        <n-input type="textarea" placeholder="请输入回复内容" v-model:value="reply_content"></n-input>
        <n-button type="info" @click="replyMessage" :loading="replying" :disabled="replying">回复留言</n-button>
      </div>
    </div>
    <div v-else>
      <n-p>在左侧点击想要查看的留言即可查看详情</n-p>
    </div>
  </div>
</template>

<script setup>
import {useUserStore} from "@/stores/user.js";
import {ref} from "vue";
import {useRequests} from "@/common/requests.js";
import {useMessage, useNotification} from "naive-ui";

const store = useUserStore()
const requests = useRequests()
const msg = useMessage()
const notify = useNotification()

const emits = defineEmits(['messageChange'])
const props = defineProps(['message'])

const reply_content = ref(null)
const replying = ref(false)
const replyMessage = () => {
  if (replying.value) {
    return false
  }

  if (!reply_content.value || reply_content.value.length === 0) {
    return msg.info('回复内容不能为空')
  }

  const message = props.message
  replying.value = true
  const data = {
    id: message.id,
    content: reply_content.value
  }
  requests.message.manager.reply(data).then(resp => {
    replying.value = false

    return resp
  }).then(resp => {
    if (resp.ret === 0) {
      reply_content.value = null
      msg.success('回复成功')

      const item = {...message, ...{reply_content: reply_content.value}}
      emits('messageChange', item)
    } else {
      msg.error(resp?.data ?? resp?.msg ?? "未知错误")
    }
  }).catch(err => {
    console.log(err)
    notify.error({title: '出错了', content: err.toString(), duration: 3000})
  })
}
</script>

<style lang="scss" scoped>
.view {
  .item {
    margin: .5rem 0;
    display: flex;

    .field {
      min-width: 3.25rem;
    }

    .value {
      flex: 1;
    }
  }

  .reply {
    margin-top: 2rem;
  }

  .reply-btn {
    margin-top: 2rem;
    display: flex;
    flex-direction: column;
    align-items: start;
    justify-content: start;

    .n-input {
      margin-bottom: 1rem;
    }
  }
}
</style>
